﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using Cisoft.Booking.Model;
using Cisoft.Booking.BLL;

public partial class Business_Booking_AddVote : WebUI.Page.SendMessagePage
{
    private BoxesBO boxesBO = new BoxesBO();
    private BoxesMO boxesMO = new BoxesMO();
    private Hashtable ht = new Hashtable();
    private ShortMessageBO smBO = new ShortMessageBO();
    private ShortMessageMO smMO = new ShortMessageMO();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindHour();
            BindContract();
            rb_Now.Checked = true;
            //div_Timing.Visible = false;
            NowOrTiming(false);
        }
    }

    #region 按钮事件
    /// <summary>
    /// 新增事件
    /// </summary>
    protected void btnSave_Click(object sender, ImageClickEventArgs e)
    {
        int flag = -1;
        string strError = "";

        #region 投票选项验证
        for (int i = 3; i <= 20; i++)
        {
            Label lbl_Option = Pan_Options.FindControl("lbl_Option" + i) as Label;
            TextBox tb_Option = Pan_Options.FindControl("tb_Option" + i) as TextBox;
            if (tb_Option.Visible == true)
            {
                if (string.IsNullOrEmpty(tb_Option.Text) && tb_Option1.Text.Trim() != "" && tb_Option2.Text.Trim() != "")
                {
                    lbl_OptionValidator.Text = "<span style='color:red;font-weight:bold;'>请填写投票选项" + i + "</span>";
                    lbl_OptionValidator.Visible = true;
                    return;
                }
                else
                {
                    lbl_OptionValidator.Visible = false;
                }
            }
        }
        #endregion

        //验证时间
        CompareTwoDateValidate();

        if (IsValid)
        {
            #region 发送事件
            //如果是立即发送
            if (rb_Now.Checked)
            {
                VoteMO vMO = new VoteMO();
                string[] mobiles = tb_Mobile.Text.Trim().Split(',');
                foreach (string mobile in mobiles)
                //foreach (ListItem li in ListBox1.Items)
                {
                    if (mobile.Length == 11)
                    {
                        //发送短信
                        try
                        {
                            vMO = FillVoteMO(GetEMATime(10));
                            SendMessage(mobile, SendMessageContent() + GetRuleSendTemplate().Replace("投票标识",vMO.VoteID.ToString()));
                        }
                        catch (Exception ex)
                        {
                            flag = 1;
                            strError = ex.Message;
                        }
                        //写入系统短信表
                        try
                        {
                            //AddSystemMsg(mobile, tb_VoteContent.Text, DateTime.Now);
                            AddSystemMsg(mobile, SendMessageContent() + GetRuleSendTemplate(), DateTime.Now);
                        }
                        catch (Exception ex)
                        {
                            flag = 2;
                            strError = ex.Message;
                        }
                        if (flag == 1)
                        {
                            PageError("发送短信失败！错误信息如下：" + strError, Request.RawUrl);
                        }
                        if (flag == 2)
                        {
                            PageError("写入系统短信失败！错误信息如下：" + strError, Request.RawUrl);
                        }
                    }
                }
                //写入投票表
                try
                {
                    new VoteBO().Add(vMO);
                    VoteOptionAdd(vMO.VoteID);
                }
                catch (Exception ex)
                {
                    flag = 3;
                    strError = ex.Message;
                }
                if (flag == -1)
                {
                    PageRight("投票发送成功!", "VoteManage.aspx", "返回管理", "");
                }
                if (flag == 3)
                {
                    PageError("写入系统投票表失败！错误信息如下：" + strError, Request.RawUrl);
                }
            }
            //如果是定时发送
            if (rb_Timing.Checked)
            {
                VoteMO vMO = new VoteMO();
                string date = tb_SendTime.Text;
                date += " " + ddl_SendHour.SelectedValue + ":" + ddl_SendMinite.SelectedValue;
                DateTime time = Convert.ToDateTime(date);
                string[] mobiles = tb_Mobile.Text.Trim().Split(',');
                foreach (string mobile in mobiles)
                {
                    if (IsMobile(mobile))
                    {
                        //发送短信
                        try
                        {
                            vMO = FillVoteMO(time);
                            SendMessage(mobile, SendMessageContent() + GetRuleSendTemplate().Replace("投票标识",vMO.VoteID.ToString()), time);
                        }
                        catch (Exception ex)
                        {
                            flag = 1;
                            strError = ex.Message;
                        }
                        //写入系统短信表
                        try
                        {
                            //AddSystemMsg(mobile, tb_VoteContent.Text, time);
                            AddSystemMsg(mobile, SendMessageContent() + GetRuleSendTemplate(), time);
                        }
                        catch (Exception ex)
                        {
                            flag = 2;
                            strError = ex.Message;
                        }
                        if (flag == 1)
                        {
                            PageError("发送短信失败！错误信息如下：" + strError, Request.RawUrl);
                        }
                        if (flag == 2)
                        {
                            PageError("写入系统短信失败！错误信息如下：" + strError, Request.RawUrl);
                        }
                    }
                }
                //写入投票表
                try
                {
                    new VoteBO().Add(vMO);
                    VoteOptionAdd(vMO.VoteID);
                }
                catch (Exception ex)
                {
                    flag = 3;
                    strError = ex.Message;
                }
                if (flag == -1)
                {
                    PageRight("投票发送成功！", "VoteManage.aspx", "返回管理", "");
                }
                if (flag == 3)
                {
                    PageError("写入系统投票表失败！错误信息如下：" + strError, Request.RawUrl);
                }
            }
            #endregion
        }
    }
    /// <summary>
    /// 返回事件
    /// </summary>
    protected void butrReset_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("VoteManage.aspx");
    }
    #endregion

    #region 添加输入的手机号码
    /// <summary>
    /// 添加手机号码s
    /// </summary>
    protected void btn_AddMobile_Click(object sender, EventArgs e)
    {
        string mobile = tb_Mobile.Text.Trim();
        if (!string.IsNullOrEmpty(mobile))
        {
            ListItem li = new ListItem();
            li.Text = mobile;
            li.Value = mobile;

            ListBox1.Items.Add(li);
            tb_Mobile.Text = "";
        }
    }
    #endregion

    #region 绑定小时时间
    /// <summary>
    /// 绑定小时时间
    /// </summary>
    private void BindHour()
    {
        for (int i = 0; i < 24; i++)
        {
            ListItem li = new ListItem();
            li.Value = i.ToString();
            li.Text = i.ToString();

            ddl_SendHour.Items.Add(li);
        }

        for (int j = 0; j < 60; j++)
        {
            ListItem item = new ListItem();
            item.Text = j.ToString();
            item.Text = j.ToString();

            ddl_SendMinite.Items.Add(item);
        }
    }
    

    /// <summary>
    /// 选中定时发送
    /// </summary>
    protected void rb_Timing_CheckedChanged(object sender, EventArgs e)
    {
        if (rb_Timing.Checked)
        {
            //div_Timing.Visible = true;
            NowOrTiming(true);
        }
    }
    /// <summary>
    /// 选中立即发送
    /// </summary>
    protected void rb_Now_CheckedChanged(object sender, EventArgs e)
    {
        if (rb_Now.Checked)
        {
            NowOrTiming(false);
        }
    }
    #endregion

    #region 点击添加联系人 
    /// <summary>
    /// 点击添加联系人
    /// </summary>
    protected void btn_AddContact_Click(object sender, EventArgs e)
    {
        //moe1.Show();
        //全选
        if (cb_SelectAll.Checked == true)
        {
            //发送人为空
            if (tb_Mobile.Text.Trim() == "")
            {
                foreach (ListItem li in ListBox1.Items)
                {
                    tb_Mobile.Text += li.Value + ",";
                }
            }
            //发送人不为空，判断是否有重复的号码
            else
            {
                foreach (ListItem li in ListBox1.Items)
                {
                    if (tb_Mobile.Text.IndexOf(li.Value) >= 0)
                    {
                    }
                    else
                    {
                        tb_Mobile.Text += li.Value + ",";
                    }
                }
            }
        }
        //不为全选
        else
        {
            //发送人为空
            if (tb_Mobile.Text.Trim() == "")
            {
                foreach (ListItem li in ListBox1.Items)
                {
                    if (li.Selected == true)
                    {
                        tb_Mobile.Text += li.Value + ",";
                    }
                }
            }
            //发送人不为空，判断是否有重复的号码
            else
            {
                foreach (ListItem li in ListBox1.Items)
                {
                    if (li.Selected == true)
                    {
                        if (tb_Mobile.Text.IndexOf(li.Value) >= 0)
                        {
                        }
                        else
                        {
                            tb_Mobile.Text += li.Value + ",";
                        }
                    }
                }
            }
        }
    }
    #endregion

    #region 绑定OA联系人 手机格式为 手机/员工姓名 void BindContract()
    /// <summary>
    /// 绑定OA联系人 手机格式为 手机/员工姓名
    /// </summary>
    private void BindContract()
    {
        //ListBox1.Items.Add(new ListItem("测试联系人/15307719728", "15307719728"));
        BindList(ListBox1);
    }
    #endregion


    #region 写入系统短信表 void AddSystemMsg(string Mobile, string Content, DateTime Time)

    /// <summary>
    /// 写入系统短信表 
    /// </summary>
    /// <param name="Mobile">接收手机号码</param>
    /// <param name="Content">短信内容</param>
    private void AddSystemMsg(string Mobile, string Content, DateTime Time)
    {
        smMO.ShortMessageID = smBO.GetMaxId();
        smMO.ShortMessageRecive = Mobile;
        smMO.ShortMessageSend = "系统";
        smMO.ShortMessageSendTime = Time;
        smMO.ShortMessageType = "投票";
        smMO.ShortMessageContent = Content;
        smMO.ID_FK = -1;

        smBO.Add(smMO);
    }
    #endregion

    #region 填充投票实体类 VoteMO FillVoteMO(DateTime SendTime)
    /// <summary>
    /// 填充投票实体类
    /// </summary>
    /// <param name="SendTime">发送时间</param>
    private VoteMO FillVoteMO(DateTime SendTime)
    {
        DateTime startTime = Convert.ToDateTime(txtDateA.Text + " 00:00:00");
        DateTime endTime = Convert.ToDateTime(txtDateB.Text + " 23:59:59"); 

        VoteMO vMO = new VoteMO();
        vMO.VoteID = new VoteBO().GetMaxId();
        vMO.VoteName = "";
        vMO.VoteResult = "";
        vMO.VoteContent = tb_VoteContent.Text;//SendMessageContent();
        vMO.VoteStartTime = startTime;
        vMO.VoteEndTime = endTime;
        vMO.VoteSendTime = SendTime;
        vMO.VoteJoin = tb_Mobile.Text;

        return vMO;
    }
    #endregion

    #region 投票选项状态
    protected void ddl_Options_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Convert.ToInt32(ddl_Options.SelectedValue) >= 2)
        {
            Panel pan_Options = this.Form.FindControl("Pan_Options") as Panel;
            foreach (Control c in pan_Options.Controls)
            {
                if (c is TextBox)
                {
                    string id = c.ID.Replace("tb_Option", "");//c.ID.Substring(c.ID.Length - 1, 1);
                    if (int.Parse(id) <= int.Parse(ddl_Options.SelectedValue))
                    {
                        Label lbl_Option = pan_Options.FindControl("lbl_Option" + id) as Label;
                        lbl_Option.Visible = true;
                        c.Visible = true;
                    }
                    else
                    {
                        Label lbl_Option = pan_Options.FindControl("lbl_Option" + id) as Label;
                        lbl_Option.Visible = false;
                        TextBox tb_Option = c as TextBox;
                        tb_Option.Text = "";
                        c.Visible = false;
                    }
                }
            }
        }
    }
    #endregion

    #region 获取投票选项状态的值 ArrayList GetValueOfOptions()
    /// <summary>
    /// 获取投票选项状态的值
    /// </summary>
    private ArrayList GetValueOfOptions()
    {
        ArrayList al = new ArrayList();

        foreach (Control c in Pan_Options.Controls)
        {
            if (c is TextBox)
            {
                TextBox tb_Option = c as TextBox;
                if (!string.IsNullOrEmpty(tb_Option.Text) && tb_Option.Visible == true)
                { 
                    string id = c.ID.Substring(c.ID.Length-1,1);
                    string strOption = tb_Option.Text;
                    al.Add(strOption);
                }
            }
        }
        return al;
    }
    #endregion

    #region 获取EMA服务器时间 DateTime GetEMATime()
    private DateTime GetEMATime()
    {
        DateTime time = new DateTime();
        time = new Cisoft.EMA.SMS().GetEMATime();
        time = time.AddSeconds(10);
        return time;
    }

    /// <summary>
    /// 获取EMA服务器时间,加入指定的秒数
    /// </summary>
    /// <param name="Seconds">多少秒后</param>
    private DateTime GetEMATime(int Seconds)
    {
        DateTime time = new DateTime();
        time = new Cisoft.EMA.SMS().GetEMATime();
        time = time.AddSeconds(Seconds);
        return time;
    }
    #endregion

    #region 比较两个时间大小 bool CompareTowTime(DateTime StartTime, DateTime EndTime)
    /// <summary>
    /// 比较两个时间大小,如果开始时间大于结束时间，返回false；如果结束时间大于开始时间，返回true
    /// </summary>
    /// <param name="StartTime">时间1</param>
    /// <param name="EndTime">时间2</param>
    private bool CompareTowTime(DateTime StartTime, DateTime EndTime)
    {
        bool flag = false;
        if (StartTime >= EndTime)
        {
            flag = false;
        }
        else
        {
            flag = true;
        }
        return flag;
    }
    #endregion

    #region 发送的消息 string SendMessageContent()
    private string SendMessageContent()
    {
        ArrayList al = GetValueOfOptions();
        StringBuilder sb = new StringBuilder();
        sb.Append(tb_VoteContent.Text);
        sb.Append("   选项:");
        if (al.Count > 0)
        {
            for (int i = 1; i <= al.Count; i++)
            {
                sb.Append(i + "、" + al[i-1].ToString() + " ");
            }
        }
        return sb.ToString();
    }
    #endregion

    #region 验证时间 void CompareTwoDateValidate()
    private void CompareTwoDateValidate()
    {
        if (Convert.ToDateTime(txtDateA.Text) >= Convert.ToDateTime(txtDateB.Text))
        {
            lbl_SendTimeValidator.Text = "<span style='color:red;font-weight:bold;'>结束时间必须大于开始时间！</span>";
            return;
        }
    }
    #endregion

    #region 写入投票选项表 void VoteOptionAdd(int VoteID)
    private void VoteOptionAdd(int VoteID)
    {
        //定义变量是否有异常，默认为无异常
        bool flag = false;
        string strError = "";
        for (int i = 1; i <= 20; i++)
        {
            Label lbl_Option = Pan_Options.FindControl("lbl_Option" + i) as Label;
            TextBox tb_Option = Pan_Options.FindControl("tb_Option" + i) as TextBox;
            if (tb_Option.Visible == true)
            {
                if (!string.IsNullOrEmpty(tb_Option.Text) && tb_Option.Visible == true)
                {
                    VoteOptionBO voBO = new VoteOptionBO();
                    VoteOptionMO voMO = new VoteOptionMO();

                    voMO.VoteOptionID = voBO.GetMaxId();
                    voMO.VoteOptionContent = tb_Option.Text;
                    voMO.VoteOptionNumber = i;
                    voMO.VoteID_FK = VoteID;
                    voMO.VoteCount = 0;

                    try
                    {
                        voBO.Add(voMO);
                    }
                    catch(Exception ex)
                    {
                        //有异常，赋值
                        flag = true;
                        strError = ex.Message;
                    }
                    if (flag)
                    {
                        PageError(strError, Request.RawUrl);
                    }
                }
            }
        }
    }
    #endregion

    #region 获取投票选项内容 string GetVoteOptions()
    private string GetVoteOptions()
    {
        string strVoteOption = "";

        for (int i = 1; i <= 20; i++)
        {
            Label lbl_Option = Pan_Options.FindControl("lbl_Option" + i) as Label;
            TextBox tb_Option = Pan_Options.FindControl("tb_Option" + i) as TextBox;
            if (tb_Option.Visible == true)
            {
                if (string.IsNullOrEmpty(tb_Option.Text))
                {
                    strVoteOption += tb_Option.Text;
                }
            }
        }

        return strVoteOption;
    }
    #endregion

    #region 获取规则表发送模板 string GetRuleSendTemplate()
    private string GetRuleSendTemplate()
    {
        string strSendTemplate = "";

        RuleBO rBO = new RuleBO();
        RuleMO rMO = new RuleMO();

        rMO = rBO.GetModel(" RuleCode like '%TP%'");
        if(rMO!=null)
        {
            strSendTemplate = rMO.RuleOrderTemplate;
        }
        return strSendTemplate;
    }
    #endregion

    #region 发送选择时间空间状态
    private void NowOrTiming(bool flag)
    {
        if (flag)
        {
            tb_SendTime.Enabled = true;
            ddl_SendHour.Enabled = true;
            ddl_SendMinite.Enabled = true;
            CalendarExtender2.Enabled = true;
        }
        else
        {
            tb_SendTime.Enabled = false;
            ddl_SendHour.Enabled = false;
            ddl_SendMinite.Enabled = false;
            CalendarExtender2.Enabled = false;
        }
    }
    #endregion
}
